<template>
  <div class="params">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片式图 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联 -->
          <el-cascader
            v-model="cateKeys"
            :options="cateList"
            :props="cascaderList"
            @change="handleChange"
            ref="cascaderHandle"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab栏 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isdisable"
            @click="showAddParamsDialog"
          >
            添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 添加新的描述 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  class="el-icon-edit"
                  size="mini"
                  @click="showEditParamsDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  class="el-icon-delete"
                  size="mini"
                  @click="removeParam(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isdisable"
            @click="showAddParamsDialog"
          >
            添加属性
          </el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 添加新的描述 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  class="el-icon-edit"
                  size="mini"
                  @click="showEditParamsDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  class="el-icon-delete"
                  size="mini"
                  @click="removeParam(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性或参数的对话框 -->
    <el-dialog
      :title="`添加${titleText}`"
      :visible.sync="addParamDialogVisible"
      width="50%"
      @close="handleAddParamClose"
    >
      <el-form
        :model="addParamForm"
        :rules="addParamFormRules"
        ref="addParamFormRef"
        label-width="90px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParam">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改属性或参数的对话框 -->
    <el-dialog
      :title="`修改${titleText}`"
      :visible.sync="editParamDialogVisible"
      width="50%"
      @close="handleEditParamClose"
    >
      <el-form
        :model="editParamForm"
        :rules="editParamFormRules"
        ref="editParamFormRef"
        label-width="90px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParam">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      cateList: [],
      cascaderList: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      cateKeys: [],
      activeName: "many",
      manyTableList: [],
      onlyTableList: [],
      addParamDialogVisible: false,
      addParamForm: {
        attr_name: "",
      },
      addParamFormRules: {
        attr_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      editParamDialogVisible: false,
      editParamForm: {},
      editParamFormRules: {
        attr_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取分类列表失败！");
      // console.log(res);
      this.cateList = res.data;
    },
    async handleChange() {
      // console.log(this.cateKeys);
      this.getParamsList();
    },
    handleTabClick() {
      // console.log(this.activeName);
      this.getParamsList();
    },
    async getParamsList() {
      if (this.cateKeys.length !== 3) {
        this.cateKeys = [];
        this.manyTableList = [];
        this.onlyTableList = [];
        return;
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("获取参数列表失败！");
      // 将获取到的attr_vals分割成数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 添加标志位，用来显示input或button
        item.inputVisible = false;
        // 添加用来保存input值的变量
        item.inputValue = "";
      });

      if (this.activeName === "many") {
        this.manyTableList = res.data;
      } else {
        this.onlyTableList = res.data;
      }
      // console.log(res);
    },
    showAddParamsDialog() {
      this.addParamDialogVisible = true;
    },
    handleAddParamClose() {
      this.$refs.addParamFormRef.resetFields();
    },
    addParam() {
      this.$refs.addParamFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        // console.log(res);
        if (res.meta.status !== 201)
          return this.$message.error(`添加${this.titleText}失败!`);
        this.$message.success(`添加${this.titleText}成功！`);
        this.getParamsList();
        this.addParamDialogVisible = false;
      });
    },
    async showEditParamsDialog(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200)
        return this.$message.error(`获取${this.titleText}失败！`);
      this.editParamForm = res.data;
      // console.log(res);
      this.editParamDialogVisible = true;
    },
    handleEditParamClose() {
      this.$refs.editParamFormRef.resetFields();
      this.editParamForm = {};
    },
    editParam() {
      this.$refs.editParamFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamForm.attr_id}`,
          {
            attr_name: this.editParamForm.attr_name,
            attr_sel: this.editParamForm.attr_sel,
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error(`修改${this.titleText}失败！`);
        this.$message.success(`修改${this.titleText}成功！`);
        this.getParamsList();
        this.editParamDialogVisible = false;
        // console.log(res);
      });
    },
    removeParam(id) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${id}`
          );
          if (res.meta.status !== 200) return this.$error("删除分类失败！");
          this.getParamsList();
          this.$message.success("删除成功!");
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 这里有一个小问题，不管是否成功添加数据库，只要添加了就会展示在页面上，所以如果添加失败，必须刷新页面
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row);
    },
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("修改参数项失败！请刷新页面！！");
      this.$message.success("修改参数项成功！");
    },
    handleClose(index, row) {
      row.attr_vals.splice(index, 1);
      this.saveAttrVals(row);
    },
  },
  computed: {
    isdisable() {
      if (this.cateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    cateId() {
      if (this.cateKeys.length === 3) {
        return this.cateKeys[2];
      }
      return null;
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
  created() {
    this.getCateList();
  },
};
</script>

<style scoped>
.cat_opt {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>